/**
 * 默认消息服务管理，对应Message模型的GRUD方法，请勿修改。
 * Created by macos on 14-9-24.
 */

var messageQ = require('../../tcpserver/message-q');

(function () {

  var MessageController = {};
  var root = this;

  /**
   * 创建消息
   * @param next
   */
  function createMessage(next) {

    Message.create(request)
      .exec(function (error, result) {
        if (error) {
          next(error);
        } else {
          next(null, result);
        }
      });
  };

  function findOneMessage(next) {

    Message.findOne(request)
      .exec(function (error, result) {
        if (error) {
          next(error);
        } else {
          next(null, result);
        }
      });
  };

  function findMessage(next) {

    Message.find(request)
      .exec(function (error, result) {
        if (error) {
          next(error);
        } else {
          next(null, result);
        }
      });
  };

  /**
   * 通过socket.io方式发送消息
   * @param message
   * @param next
   */
  function publishBySocketIO(next, results) {

    var message = results['message'];
    if (_.has(message, 'id')) {

      var publicMessage = {id: message.id, toUserNames: message.toUserNames};
      Message.publishCreate(publicMessage);

      next(null, publicMessage);
    } else {
      next('create message failure!')
    }

  }

  /**
   * 通过tcp socket方式发送消息
   * @param message
   * @param next
   */
  function publishBySocketTCP(next, results) {

    var message = results['message'];

    if (_.has(message, 'id')) {

      Device.find({username:message.toUserNames})
        .exec(function(err, devices) {
          if (err) {
            next(err);
            return;
          }

          //将消息发送多个设备
          async.concat(devices, function(device, callback){

            messageQ.sendClient(device, JSON.stringify(message.content), function(err, status){
              callback(null, {uuid:device.uuid, status:status});

            });

          }, function(err, result){

            Message.update({id: message.id}, {socketTcp:result})
              .exec(function(err, messages){
                if (err) {
                  sails.log.error(err);
                  return;
                }
            });
            next(null, result);
          })

        });

    } else {
      next('create message failure!')
    }
  }

  MessageController.send = function (req, res) {
    var action = req.param('action');
    root.request = req.body;

    async.auto({
      message: createMessage,
      socketIO: ['message', publishBySocketIO],
      socketTCP: ['message', publishBySocketTCP]
    }, function (error, results) {
      if (error) {
        res.jsonResponse(400, error);
      } else {
        res.jsonResponse(200, results);
      }
    });

  };

  MessageController.connBySocketIO = function (req, res) {
    Message.watch(req);
    res.jsonResponse(200, 'Message with socket.io id ' + sails.sockets.id(req) + ' is now subscribed to the model class \'Message\'.');
  }

  MessageController.receive = function (req, res) {
    root.request = req.body;

    if (req.session.user.username === root.request.toUserNames) {

      async.waterfall([
        findOneMessage
      ], function (error, result) {
        if (error) {
          res.jsonResponse(400, error);
        } else {
          res.jsonResponse(200, result);
        }
      });

    } else {
      res.jsonResponse(400, 'You can not receive this message');
    }

  }

  MessageController.findToMe = function (req, res) {
    root.request = req.body;

    if (root.request.where && _.contains(root.request.where.toUserNames, req.session.user.username)) {
      async.waterfall([
        findMessage
      ], function (error, result) {
        if (error) {
          res.jsonResponse(400, error);
        } else {
          res.jsonResponse(200, result);
        }
      });
    } else {
      res.jsonResponse(400, 'You can not find these ones');
    }

  }

  module.exports = MessageController;

}());